// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.cpu;

import com.dustedpixels.jasmin.common.Timeline;
import com.dustedpixels.jasmin.memory.Memory;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class CrewMemoryKitBenchmark {
  public void run(int count, int bufferSize, int steps) throws Exception {
    Timeline rwTimeline = new TimelineImpl();
    Memory rwMemory = new ZeroMemory();
    
    Timeline[] roTimelines = new Timeline[count];
    Memory[] roMemories = new Memory[count];
    for (int i = 0; i < count; i++) {
      roTimelines[i] = new TimelineImpl();
      roMemories[i] = new ZeroMemory();
    }
    
    CrewMemoryKit memoryKit = new CrewMemoryKit(
        roTimelines,
        rwTimeline,
        roMemories,
        rwMemory,
        bufferSize);
    
    Thread rwThread = new Thread(new MemoryWriter(rwTimeline, memoryKit.getEwMemory(), steps));
    rwThread.start();
    
    Thread[] roThreads = new Thread[count];
    for (int i = 0; i < count; i++) {
      roThreads[i] = new Thread(new MemoryReader(roTimelines[i], memoryKit.getCrMemories()[i], steps));
      roThreads[i].start();
    }
    
    rwThread.join();
    
    for (int i = 0; i < count; i++) {
      roThreads[i].join();
    }
  }
  
  public static void main(String[] args) throws Exception {
    CrewMemoryKitBenchmark benchmark = new CrewMemoryKitBenchmark();
    
    System.out.println("Warmup...");
    long millis = System.currentTimeMillis();
    benchmark.run(1, 1024, 3500000);
    millis = System.currentTimeMillis() - millis;
    System.out.println("Warmed up in " + millis + "ms");

    System.out.println("Run...");
    millis = System.currentTimeMillis();
    benchmark.run(1, 1024, 3500000);
    millis = System.currentTimeMillis() - millis;
    System.out.println("Ran in " + millis + "ms");
  }
}
